#include "pm/costevolution.h"
#include <wx/log.h>

using namespace pm;


CostEvolution::CostEvolution()
{
}

bool CostEvolution::load(wxSQLite3ResultSet& res)
{
	double lastCost  = 0.0;
	double lastTask  = 0.0;
	bool   bHaveTask = false;
	while (res.NextRow()) {
		lastCost += res.GetDouble(wxT("cost"), 0.0);
		
		if (bHaveTask == false && res.IsNull(wxT("task")) == false) {
			// Do not add tasks before it's necessary
			bHaveTask = true;
			lastTask  = lastCost;
		}
		lastTask += res.GetDouble(wxT("task"), 0.0);
		
		Month month;
		month.cost   = lastCost;
		month.todo   = lastTask;
		month.month  = res.GetString(wxT("month"));
		m_months.push_back(month);
		
		wxLogMessage(wxT("Adding month %s : cost = %.2f, task = %.2f"), month.month().c_str(), lastCost, lastTask);
	}
	
	if (m_months.empty()) {
		return true;
	}
	
	// Remove unnecessary costs
	VectorMonth::reverse_iterator itMonth1 = m_months.rbegin();
	VectorMonth::reverse_iterator itMonth2 = itMonth1;
	for (++itMonth2; itMonth2 != m_months.rend(); ++itMonth1, ++itMonth2) {
		if (itMonth2->cost() != itMonth1->cost()) {
			break;
		}
		itMonth1->cost = 0.0;
		wxLogMessage(wxT("remove cost of month %s (last cost = %.2f, cost = %.2f)"), itMonth1->month().c_str(), itMonth2->cost(), itMonth1->cost());
	}
	return true;
}


const char* GetCostEvolutionByProject::QUERY = 
"select                       "
"	id_project,               "
"	work_request,             "
"	task,                     "
"	cost,                     "
"	month                     "
"from view_monthly_cost_evol  "
"where id_project = ?         "
"order by month asc           "
;

GetCostEvolutionByProject::GetCostEvolutionByProject(const db::ID& idProject)
: id_project(idProject)
{
}
	
bool GetCostEvolutionByProject::query(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt =  db.PrepareStatement(QUERY);
	stmt.Bind(1, id_project());
	wxSQLite3ResultSet res = stmt.ExecuteQuery();
	return m_evolution.load(res);
}
